using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using DICE_GS;

[System.Serializable]
public class DiceIcon
{
	public GameObject obj;
	public bool isActive;
	public bool isMoving;
	public int nDiceNum;
	public int posIndex;
	public bool isAttacker;
	public bool isSideChangedBySwap;

	public void Activate( DiceIconPrefab iconPrefab, int num, int _posIndex, bool _isAttacker)
	{
		isSideChangedBySwap = false;
		isMoving = false;
		isActive = true;
		posIndex = _posIndex;
		isAttacker = _isAttacker;
		obj = iconPrefab.gameObject;
		nDiceNum = num;
		if(_isAttacker)
			obj.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_yellow_0" + num.ToString());
		else
			obj.GetComponent<tk2dSprite>().SetSprite("icon_dice_ingame_blue_0" + num.ToString());

	}

	public void DetachParent()
	{
		if(isActive)
			obj.transform.parent = null;
	}
	
	public void FadeOutDelete(float speed)
	{
		if(isActive)
			obj.GetComponent<DiceIconPrefab>().ChangeAlpha(0.0f, speed, true );
		isActive = false;
		isMoving = false;
	}

	public bool IsValidFind()
	{
		if(isActive && !isMoving && !isSideChangedBySwap)
			return true;
		return false;
	}
}

public enum BattleNumSound
{
	None,
	Small,
	Big
}


public class BattleManager : MonoBehaviour {
	
	private static BattleManager instance;

	public static BattleManager Instance{
		get{
			return instance;
		}
	}	
	public float battleNumYOffset = 0.174f;//0.124f;
	public BattleNumSound battleNumSound;
	public bool isBattleResultDone;
	public bool isWinnerActionDone;
	public bool isLoserActionDone;
	public bool bCombatHappened;
	public int winnerID;
	public int loserID;	
	public int combatHappenBoardID;
//	public GameObject battleResultNumPrefab;
	public GameObject battleResultNumPrefabNew;
	//public GameObject battleResultNumPrefab_attacker;
	//public GameObject battleResultNumPrefab_defender;
	public bool waitCombatResultShow;
	public bool isRedice;
	public bool isRediceBattleDoing;
	public bool isRematchBattleDoing;
	public bool isRematch;
	public bool bDiceRolledDuringBattle;
	public bool bWaitAIThinking;
	public int maxCombatCount;
	public int combatCount;
	public int nAttackerDice;
	public int nDefenderDice;
	public bool attackerCanGetBonus;
	public bool defenderCanGetBonus;
	
	public int [] attackerDice;
	public int [] defenderDice;
	public int attackerDiceCount;
	public int defenderDiceCount;
	
	public int [] attackerGiveDice;
	public int [] attackerGetDice;
	public int [] attackerAddDice;
	public int [] defenderAddDice;
	public int [] defenderGiveDice;
	public int [] defenderGetDice;
	public int attackerAddDiceCount;
	public int defenderAddDiceCount;
	public int attackerSwapDiceCount;
	public int defenderSwapDiceCount;
	public int [] attackerDelDice;
	public int [] defenderDelDice;
	public int attackerDelDiceCount;
	public int defenderDelDiceCount;	
	
	public int [] attackerBonusDiceList;
	public int [] defenderBonusDiceList;
	public DiceIcon [] attackerDiceIcon;
	public DiceIcon [] defenderDiceIcon;
	public DiceIcon [] attackerAddDiceIcon;
	public DiceIcon [] defenderAddDiceIcon;
	public DiceIconPrefab diceIconPrefab;
	public int totalAttackerBonus;
	public int totalDefenderBonus;
	public Vector3 winnerPos;
	public int nTypeBattleResultUI;
	public Color attackColor;
	public Color defenderColor;
	
	
	public GameObject attackerNum;
	public GameObject defenderNum;
	public GameObject doubleNumPrefab_attacker;
	public GameObject doubleNumPrefab_defender;
	public GameObject attackerDoubleObj;
	public GameObject defenderDoubleObj;	
	public bool isAttackResultDone;
	public bool isDefendResultDone;
	public int attackerID;
	public int defenderID;
	public BoardPerson attacker;
	public BoardPerson defender;
	public float numOffset_x = 0.172f;
	public float numOffset_y = 0.373f;
	public int deltaHPByAttack;
	public int attackedSID;
	public int attackedSlot;
	public bool isSwapMoveDone;
	//tk2dTextMesh attackerTextMesh;
	//tk2dTextMesh defenderTextMesh;
	PlayMakerFSM attackerNumFsm;
	PlayMakerFSM defenderNumFsm;
	
	public int attackerMultiplier;
	public int defenderMultiplier;
	bool isDouble;
	Queue<PC_OP_COMBAT_RESULT> combatQueue = new Queue<PC_OP_COMBAT_RESULT>();
	
	public bool isDuringBattle;
	public int pushBackDelta;
	public bool isDrawVicroty;
	public bool isDrawDefeat;
	public bool elementBattleEnded;

	List<DiceIcon> candidateDiceIcons = new List<DiceIcon>();
	DiceIcon iconSwappedToDefender;
	DiceIcon iconSwappedToAttacker;

	void Awake()
	{
		instance = this;
		
		attackerBonusDiceList = new int[6];
		defenderBonusDiceList = new int[6];
		attackerDice = new int[2];
		defenderDice = new int[2];
		attackerAddDice = new int[2];
		attackerGiveDice = new int[2];
		attackerGetDice = new int[2];
		defenderAddDice = new int[2];		
		defenderGiveDice = new int[2];		
		defenderGetDice = new int[2];		
		attackerDelDice = new int[2];
		defenderDelDice = new int[2];		
	}
	
	// Use this for initialization
	void Start () 
	{
			
	}


	public void ClearBattle()
	{
		SetMaxCombatCount(0);
		combatCount = 0;
		ClearCombatQueue();
		isBattleResultDone = true;
		bCombatHappened = false;
		pushBackDelta = 0;
		SetWinnerActionDone();
		isLoserActionDone = true;
		DetachDiceIcon();
		ClearNumAndIcons();
	}
	
	public void MakeBattleEffect()
	{
		attackerNum = Instantiate(battleResultNumPrefabNew) as GameObject;
		defenderNum = Instantiate(battleResultNumPrefabNew) as GameObject;
		attackerNum.SetActive(false);
		defenderNum.SetActive(false);
		
		attackerNumFsm = attackerNum.GetComponent<PlayMakerFSM>();
		defenderNumFsm = defenderNum.GetComponent<PlayMakerFSM>();

		ObjectPool.CreatePool(diceIconPrefab);
	}
	
	public bool IsDuringBattleWithMe()
	{
		if(isDuringBattle)
		{
			if(attacker.isMe || defender.isMe)
				return true;
		}
		
		return false;
	}
	
	public bool IsBattleJoiner(int sid)
	{
		if(sid == attackerID || sid == defenderID)
			return true;
		return false;
	}
	
	public void SetWinnerActionDone()
	{
		isWinnerActionDone = true;
		Camera.main.gameObject.GetComponent<CameraControl>().isPreventChangeFocus = false;
	}
	
	public void ReserveCombatPacket(PC_OP_COMBAT_RESULT packet)
	{
		combatQueue.Enqueue(packet);
	}
	
	public void ClearCombatQueue()
	{
		combatQueue.Clear();
	}	
	
	public void SetAttackerDice(int i, int dice, int count)
	{
		attackerDice[i] = dice;
		attackerDiceCount = count;
	}

	public void SetDefenderDice(int i, int dice, int count)
	{
		defenderDice[i] = dice;
		defenderDiceCount = count;
	}

	public void SetAttackerAddDice(int i, int dice, int count)
	{
		attackerAddDice[i] = dice;
		attackerAddDiceCount = count;
	}

	public void SetDefenderAddDice(int i, int dice, int count)
	{
		defenderAddDice[i] = dice;
		defenderAddDiceCount = count;
	}
	public void SetAttackerDelDice(int i, int dice, int count)
	{
		attackerDelDice[i] = dice;
		attackerDelDiceCount = count;
	}

	public void SetDefenderDelDice(int i, int dice, int count)
	{
		defenderDelDice[i] = dice;
		defenderDelDiceCount = count;
	}
	
	public void SetAttackerSwapDice(int i, int givedice, int getdice, int count)
	{
		attackerGiveDice[i] = givedice;
		attackerGetDice[i] = getdice;
		attackerSwapDiceCount = count;
	}	

	public void SetDefenderSwapDice(int i, int givedice, int getdice, int count)
	{
		defenderGiveDice[i] = givedice;
		defenderGetDice[i] = getdice;
		defenderSwapDiceCount = count;
	}		
	
	public void SetAttackerDefender(BoardPerson attackerPerson, BoardPerson defenderPerson, int _attackerMultiplier, int _defenderMultiplier)
	{
		attacker = attackerPerson;
		defender = defenderPerson;
		attackerMultiplier = _attackerMultiplier;
		defenderMultiplier = _defenderMultiplier;
		CardManager.Instance.SetEnableAllCardScaleChange(attacker.SID, false);
		CardManager.Instance.SetEnableAllCardScaleChange(defender.SID, false);		
	}
	
	public void SetAttackerBonusDice( int sid, int [] bonusDiceList, int count)
	{
		attackerID = sid;
		totalAttackerBonus = 0;
		for(int i=0; i<count;i++)
		{
			if( i == count-1)
				attackerBonusDiceList[0] += bonusDiceList[i];
			attackerBonusDiceList[i] = bonusDiceList[i];
			totalAttackerBonus += bonusDiceList[i];
		}
		//for test
//		totalAttackerBonus = 5;
//		for(int i=0; i<count;i++)
//		{
//			attackerBonusDiceList[i] = 1;
//		}
	}

	public void SetDefenderBonusDice(  int sid, int [] bonusDiceList, int count)
	{
		defenderID = sid;
		totalDefenderBonus = 0;
		for(int i=0; i<count;i++)
		{
			if( i == count-1)
				defenderBonusDiceList[0] += bonusDiceList[i];
			defenderBonusDiceList[i] = bonusDiceList[i];
			totalDefenderBonus += bonusDiceList[i];
		}
		//for test
//		totalDefenderBonus = 5;
//		for(int i=0; i<count;i++)
//		{
//			defenderBonusDiceList[i] = 1;
//		}		
	}
	
	public void CheckShowBattleResult(int attacker, int defender, bool _attackerCanGetBonus, bool _defenderCanGetBonus, Vector3 pos)
	{
		StageManagerWrapper.camControl.SetBattleCameraFocus(true);
		attackerCanGetBonus = _attackerCanGetBonus;
		defenderCanGetBonus	= _defenderCanGetBonus;
		nAttackerDice = attacker;
		nDefenderDice = defender;
		winnerPos = pos;
		StartCoroutine("CoShowBattleResult");
	}
	
	public void ShowBattleResultAfterMoveDone(Vector3 pos)
	{
		if(waitCombatResultShow)
			ShowBattleResult(pos);
		waitCombatResultShow = false;
	}
	
	IEnumerator CoShowBattleResult()
	{
		//yield return new WaitForSeconds(0.3f);
		yield return new WaitForSeconds(0.01f);

		while(BoardManager.Instance.isWaitingForBoardPersonMoving || BoardManager.Instance.isBoardPersonMoving || !BoardManager.Instance.isShowDiceUIDone)
			yield return null;

		//if(BoardManager.Instance.isWaitingForBoardPersonMoving || BoardManager.Instance.isBoardPersonMoving || !BoardManager.Instance.isShowDiceUIDone)
		//	waitCombatResultShow = true;
		//else
		//{
			/*
			if( attacker.curBoardTile == defender.curBoardTile && combatCount==0)
			{
				while(!attacker.isFallDone)
					yield return null;
				glog.debug("same board together... attacker moveto pos  "+Time.time);
				attacker.MoveToAttackerPos();
				yield return new WaitForSeconds(0.5f);
				glog.debug("same board together... proceed  "+Time.time);
			}*/
			
			ShowBattleResult(winnerPos);
		//}
	}
	
	public void ShowBattleResult(Vector3 pos)
	{
		BoardManager.Instance.DeactivateDiceOverHead(true);
		StartCoroutine(ShowResult(pos));
	}

	public void ShowAttackerDiceIcon(Vector3 [] iconPos)
	{
		//StartCoroutine("CoShowAttackerDiceIcon", iconPos);
		glog.debug("showAttackerDiceIcon "+attackerDice[0]+"  "+attackerDice[1]);

//		Vector3 newPos = attackerTextMesh.renderer.bounds.center;
//		if(IsPersonLeftSide(attacker))
//			newPos.x -= (attackerTextMesh.renderer.bounds.extents.x + 0.1f);
//		else
//			newPos.x += attackerTextMesh.renderer.bounds.extents.x + 0.1f;
//		newPos.y += 0.06f;

		attackerDiceIcon[0].Activate( ObjectPool.Spawn (diceIconPrefab, iconPos[0]) as DiceIconPrefab , attackerDice[0], 0, true);
		//yield return new WaitForSeconds(0.01f);
//		newPos.y -= 0.06f;
//		newPos.y -= 0.06f;

		attackerDiceIcon[1].Activate( ObjectPool.Spawn (diceIconPrefab, iconPos[1]) as DiceIconPrefab , attackerDice[1], 1, true);

		attackerDiceIcon[0].obj.transform.parent = attackerNum.transform;
		attackerDiceIcon[1].obj.transform.parent = attackerNum.transform;
	}
	/*
	IEnumerator CoShowAttackerDiceIcon(Vector3 [] iconPos)
	{
		glog.debug("showAttackerDiceIcon "+attackerDice[0]+"  "+attackerDice[1]);
		Vector3 newPos = attackerTextMesh.renderer.bounds.center;
		if(IsPersonLeftSide(attacker))
			newPos.x -= (attackerTextMesh.renderer.bounds.extents.x + 0.1f);
		else
			newPos.x += attackerTextMesh.renderer.bounds.extents.x + 0.1f;
		newPos.y += 0.06f;
		attackerDiceIcon[0].Activate( Instantiate(diceIconPrefab, iconPos[0], Quaternion.identity) as GameObject , attackerDice[0], 0, true);
		//yield return new WaitForSeconds(0.01f);
		newPos.y -= 0.06f;
		newPos.y -= 0.06f;
		attackerDiceIcon[1].Activate( Instantiate(diceIconPrefab, iconPos[1], Quaternion.identity) as GameObject , attackerDice[1], 1, true);
		
	}
	*/
	void RepositionDiceIcon(BoardPerson person, tk2dTextMesh textMesh, DiceIcon [] diceIcon)
	{
		for(int i=0; i<2; i++)
		{
			if(diceIcon[i].isActive)
			{
				Vector3 newPos = diceIcon[i].obj.transform.position;
				if(IsPersonLeftSide(person))
					newPos.x -= (textMesh.renderer.bounds.extents.x + 0.1f);
				else
					newPos.x += (textMesh.renderer.bounds.extents.x + 0.1f);		
			}
		}
	}

	public void ShowDefenderDiceIcon(Vector3 [] iconPos)
	{
		//StartCoroutine("CoShowDefenderDiceIcon", iconPos);
		glog.debug("ShowDefenderDiceIcon "+defenderDice[0]+"  "+defenderDice[1]);

//		Vector3 newPos = defenderTextMesh.renderer.bounds.center;
//		if(IsPersonLeftSide(defender))
//			newPos.x -= defenderTextMesh.renderer.bounds.extents.x + 0.1f;
//		else
//			newPos.x += defenderTextMesh.renderer.bounds.extents.x + 0.1f;
//		newPos.y += 0.06f;
		
		defenderDiceIcon[0].Activate( ObjectPool.Spawn (diceIconPrefab, iconPos[0]) as DiceIconPrefab , defenderDice[0], 0, false);
		//yield return new WaitForSeconds(0.01f);

//		newPos.y -= 0.06f;
//		newPos.y -= 0.06f;

		defenderDiceIcon[1].Activate(  ObjectPool.Spawn (diceIconPrefab, iconPos[1]) as DiceIconPrefab , defenderDice[1], 1, false);

		defenderDiceIcon[0].obj.transform.parent = defenderNum.transform;
		defenderDiceIcon[1].obj.transform.parent = defenderNum.transform;
	}

	/*
	IEnumerator CoShowDefenderDiceIcon(Vector3 [] iconPos)
	{
		glog.debug("ShowDefenderDiceIcon "+defenderDice[0]+"  "+defenderDice[1]);
		Vector3 newPos = defenderTextMesh.renderer.bounds.center;
		if(IsPersonLeftSide(defender))
			newPos.x -= defenderTextMesh.renderer.bounds.extents.x + 0.1f;
		else
			newPos.x += defenderTextMesh.renderer.bounds.extents.x + 0.1f;
		newPos.y += 0.06f;
		
		defenderDiceIcon[0].Activate( Instantiate(diceIconPrefab, iconPos[0], Quaternion.identity) as GameObject , defenderDice[0], 0, false);
		//yield return new WaitForSeconds(0.01f);
		newPos.y -= 0.06f;
		newPos.y -= 0.06f;
		defenderDiceIcon[1].Activate(  Instantiate(diceIconPrefab, iconPos[1], Quaternion.identity) as GameObject , defenderDice[1], 1, false);
	}
	*/

	public void DetachDiceIcon()
	{
		attackerDiceIcon[0].DetachParent();
		attackerDiceIcon[1].DetachParent();
		defenderDiceIcon[0].DetachParent();
		defenderDiceIcon[1].DetachParent();
	}

	void FadeOutDiceIcons()
	{
		for(int i=0; i<2;i++)
		{
			attackerDiceIcon[i].FadeOutDelete(2.5f);
			defenderDiceIcon[i].FadeOutDelete(2.5f);
		}
		for(int i=0; i<attackerAddDiceCount; i++)
			attackerAddDiceIcon[i].FadeOutDelete(2.5f);
		for(int i=0; i<defenderAddDiceCount; i++)
			defenderAddDiceIcon[i].FadeOutDelete(2.5f);
			
	}
	
//	void DestroyDiceIcon()
//	{
//		Destroy(attackerDiceIcon[0]);
//		Destroy(attackerDiceIcon[1]);
//		Destroy(defenderDiceIcon[0]);
//		Destroy(defenderDiceIcon[1]);
//		
//		Destroy(attackerAddDiceIcon[0]);
//		Destroy(attackerAddDiceIcon[1]);
//		Destroy(defenderAddDiceIcon[0]);
//		Destroy(defenderAddDiceIcon[1]);
//	}
	
	DiceIcon FindAttackerIcon(int diceNum)
	{
		candidateDiceIcons.Clear();
		for(int nDice=0; nDice<attackerDiceCount; nDice++)
		{
			if( diceNum == attackerDice[nDice])
			{
				if(attackerDiceIcon[nDice].IsValidFind() )//   attackerDiceIcon[nDice].isActive && !attackerDiceIcon[nDice].isMoving && !attackerDiceIcon[nDice].isSideChangedBySwap)
				{
					candidateDiceIcons.Add ( attackerDiceIcon[nDice]);
					//return attackerDiceIcon[nDice];
				}
			}
		}

		for(int nDice=0; nDice<attackerAddDiceCount; nDice++)
		{
			if( diceNum == attackerAddDice[nDice])
			{
				if(attackerAddDiceIcon[nDice].IsValidFind() )
				{
					candidateDiceIcons.Add ( attackerAddDiceIcon[nDice]);
					//return attackerAddDiceIcon[nDice];
				}
			}
		}

		if(iconSwappedToAttacker!=null && iconSwappedToAttacker.nDiceNum == diceNum)
			candidateDiceIcons.Add (iconSwappedToAttacker);

		if(candidateDiceIcons.Count==0)
			return null;
		else
		{
			int nSelected = Random.Range( 0, candidateDiceIcons.Count);
			return candidateDiceIcons[nSelected];
		}
	}

	DiceIcon FindDefenderIcon(int diceNum)
	{
		candidateDiceIcons.Clear();
		for(int nDice=0; nDice<defenderDiceCount; nDice++)
		{
			if( diceNum == defenderDice[nDice])
			{
				if(defenderDiceIcon[nDice].IsValidFind())
				{
					candidateDiceIcons.Add ( defenderDiceIcon[nDice]);
					//return defenderDiceIcon[nDice];
				}
			}
		}

		for(int nDice=0; nDice<defenderAddDiceCount; nDice++)
		{
			if( diceNum == defenderAddDice[nDice])
			{
				if(defenderAddDiceIcon[nDice].IsValidFind())
				{
					candidateDiceIcons.Add ( defenderAddDiceIcon[nDice]);
					//return defenderAddDiceIcon[nDice];
				}
			}
		}	

		if(iconSwappedToDefender!=null && iconSwappedToDefender.nDiceNum == diceNum)
			candidateDiceIcons.Add (iconSwappedToDefender);

		if(candidateDiceIcons.Count==0)
			return null;
		else
		{
			int nSelected = Random.Range( 0, candidateDiceIcons.Count);
			return candidateDiceIcons[nSelected];
		}
	}	
	
	IEnumerator ShowResult(Vector3 pos)
	{
		bDiceRolledDuringBattle = false;
		BoardManager.Instance.isAttackerBattleRolled = false;
		BoardManager.Instance.isAttackerAIThinkingShowed = false;
		BoardManager.Instance.bWaitDefenderAIThink = false;
		StageManagerWrapper.manager.bAIBattleDiceRollImmediately = false;

		attacker.bWaitCombatRoll_attacker = false;
		attacker.bWaitCombatRoll_defender = false;
		attacker.bWaitActivateDiceOverHead_aibattle = false;
		attacker.bWaitActivateDiceOverHead = false;

		defender.bWaitCombatRoll_attacker = false;
		defender.bWaitCombatRoll_defender = false;
		defender.bWaitActivateDiceOverHead_aibattle = false;
		defender.bWaitActivateDiceOverHead = false;

		UIManager.Instance.DisableSkillBar(true);
		UIManager.Instance.BlackFocus(true);
		if(attacker.tagOverHead!=null)
			attacker.tagOverHead.SetActive(false);
		if(defender.tagOverHead!=null)
			defender.tagOverHead.SetActive(false);

//		if(attacker.SID != BoardManager.Instance.curTurnSID)
//		{
//			attacker.PlayAlarmParticle();
//		}
//		if(defender.SID != BoardManager.Instance.curTurnSID)
//		{
//			defender.PlayAlarmParticle();
//		}

		while(attacker.isTeleportDoing)
			yield return null;
		//for attacker, defender not exist on battle tile ( happens at continue game)
		if(attacker.curBoardTile.boardInfo.id != combatHappenBoardID)
		{
			Debug.LogError("attacker not exist on battle tile. force set board "+combatHappenBoardID);
			BoardTile combatTile = PathManager.Instance.GetBoardTile(combatHappenBoardID);
			if(combatTile!=null)
				attacker.SetInitialCurrentBoard(combatTile, true, 1);
		}
		if(defender.curBoardTile.boardInfo.id != combatHappenBoardID)
		{
			Debug.LogError("defender not exist on battle tile. force set board "+combatHappenBoardID);
			BoardTile combatTile = PathManager.Instance.GetBoardTile(combatHappenBoardID);
			if(combatTile!=null)
				defender.SetInitialCurrentBoard(combatTile, true, 1);
		}
		
		if(!attacker.bMovedToBattlePosition)
		{
			attacker.MoveToAttackerPos();
			yield return new WaitForSeconds(0.5f);
		}		
		
		//while(!attacker.bFaceToBattleOpponent || !defender.bFaceToBattleOpponent)
		//{
		//	yield return null;
		//}


		attacker.ReCalculateZ_SameTileBattle();

		attackerNum.transform.parent = null;
		defenderNum.transform.parent = null;

		if(!attackerNum.activeSelf)
		{
			attackerNum = ShowBattleNum(true, attackerNum, nAttackerDice);
			Vector3 [] diceIconPos = { Vector3.zero, Vector3.zero};
			ShowAttackerDiceIcon(diceIconPos);
			attackerDiceIcon[0].obj.transform.localPosition = new Vector3( -0.06f, -0.162f, 1);
			attackerDiceIcon[1].obj.transform.localPosition = new Vector3( 0.06f, -0.162f, 1);
		}
		if(!defenderNum.activeSelf)
		{
			defenderNum = ShowBattleNum(false, defenderNum, nDefenderDice); 
			Vector3 [] diceIconPos = { Vector3.zero, Vector3.zero};
			ShowDefenderDiceIcon(diceIconPos);
			defenderDiceIcon[0].obj.transform.localPosition = new Vector3( -0.06f, -0.162f, 1);
			defenderDiceIcon[1].obj.transform.localPosition = new Vector3( 0.06f, -0.162f, 1);
		}

		// for exception cases(continue battle) , re set position
		SetNumOffset( nAttackerDice, attackerNum, attacker);
		SetNumOffset( nDefenderDice, defenderNum, defender);

		DetachDiceIcon();


		if( !StageManagerWrapper.camControl.EventZoomIn() )
			StageManagerWrapper.camControl.BackToDefaultOrtho();
		StageManagerWrapper.camControl.bProceedingDestMarkZoom = false;
//		Vector3 newBattleEffPos = pos;
//		newBattleEffPos.z = -1;
//		GameObject battleEff = Instantiate(battleEffect, newBattleEffPos, Quaternion.identity) as GameObject;
//		Destroy(battleEff, 1.0f);
		combatCount++;
		CardManager.Instance.battleManagerCombatCount = combatCount;
		glog.debug("showresult maxCombatCount="+maxCombatCount+"  combatcount="+combatCount);
		if(combatCount==1)
		{
			SoundManager.Instance.PlaySound(0);
		}
			//yield return new WaitForSeconds(0.1f);
		
		CardManager.Instance.isElementFX = false;
		
		if(attackerCanGetBonus && !defenderCanGetBonus)
		{
			CardManager.Instance.isElementFX = true;
			bool check1 = CardManager.Instance.CardBattleStart(attacker, defender ,true, true);
			bool check2 = CardManager.Instance.CardBattleStart(defender, attacker ,true, false);	
			if(!check1 && !check2)
				CardManager.Instance.isElementFX = false;
		}
		else if(!attackerCanGetBonus && defenderCanGetBonus)
		{
			CardManager.Instance.isElementFX = true;
			bool check1 = CardManager.Instance.CardBattleStart(attacker, defender, true, false);
			bool check2 = CardManager.Instance.CardBattleStart(defender, attacker, true, true);	
			if(!check1 && !check2)
				CardManager.Instance.isElementFX = false;
		}
		else
		{
			CardManager.Instance.CardBattleStart(attacker, defender, false, false);
			CardManager.Instance.CardBattleStart(defender, attacker, false, false);				
		}
	
		if(CardManager.Instance.isElementFX)
		{
			while( CardManager.Instance.isElementFX)
				yield return null;
		}
		else
			yield return new WaitForSeconds(IngameSetting.Instance.PopCardDelay);

		elementBattleEnded = true;
		attacker.CheckAbnormalReserve();
		defender.CheckAbnormalReserve();
		isRediceBattleDoing = false;
		isRematchBattleDoing = false;
		//battleNumSound = BattleNumSound.None;
		yield return new WaitForSeconds(0.5f);
		isAttackResultDone = false;
		isDefendResultDone = false;			
		int nAttackNum = nAttackerDice;
		
		if(totalAttackerBonus>0 && !HaveToShowDetail(attackerID))
			attackerNum = ShowBattleNum(true,attackerNum, nAttackNum + totalAttackerBonus); 
		//else
		//	attackerNum = ShowBattleNum(true,attackerNum, nAttackNum); 
		
		//StartCoroutine("CoShowAttackerDiceIcon");
		
		StartCoroutine(ShowDefenderResult(pos));
		
		if(totalAttackerBonus>0 && HaveToShowDetail(attackerID))
		{
			float timeAdd = 0.0f;
			int nCount=0;
			int tempTotalAttackerBonus = totalAttackerBonus;
			while(tempTotalAttackerBonus>0)
			{
				timeAdd += Time.deltaTime;
				if(timeAdd > 0.1f) 
				{
					if(nCount==0)
					{
						for(int i=0; i< 5; i++) 
						{
							int addValue = attackerBonusDiceList[i];
							if(addValue>0) {
								ShowMoveBonus(attacker, attackerNum.transform, i, "number_", addValue, DiceShapeType.Attacker);
							}
						}
						yield return new WaitForSeconds(0.8f);
						yield return new WaitForSeconds(IngameSetting.Instance.MoveBonusDelay);
					}
					battleNumSound = BattleNumSound.Small;
					attackerNum = ShowBattleNum(true, attackerNum, ++nAttackNum); 
					tempTotalAttackerBonus--;
					nCount++;
					timeAdd = 0.0f;
				}
				yield return null;
			}
			
			isAttackResultDone = true;
			//BoardManager.Instance.isBattleResultDone = true;
		}
		else
			isAttackResultDone = true;
		
		
		
	}
	
	IEnumerator ShowDefenderResult(Vector3 pos)
	{
		yield return new WaitForSeconds(0.15f);		
		battleNumSound = BattleNumSound.Big;
		int nNum = nDefenderDice;
		if(totalDefenderBonus>0 && !HaveToShowDetail(defenderID))
			defenderNum = ShowBattleNum(false, defenderNum, nNum+totalDefenderBonus); 
		//else
		//	defenderNum = ShowBattleNum(false, defenderNum, nNum); 
		
		//StartCoroutine("CoShowDefenderDiceIcon");
		
		if(totalDefenderBonus>0 && HaveToShowDetail(defenderID))
		{
			float timeAdd = 0.0f;
			int nCount=0;
			int tempTotalDefenderBonus = totalDefenderBonus;
			while(tempTotalDefenderBonus>0)
			{
				timeAdd += Time.deltaTime;
				if(timeAdd > 0.1f) 
				{
					if(nCount==0)
					{
						for(int i=0; i< 5; i++) 
						{
							int addValue = defenderBonusDiceList[i];
							if(addValue>0) {
								ShowMoveBonus(defender, defenderNum.transform, i, "number_", addValue, DiceShapeType.Defender);
							}
						}
						yield return new WaitForSeconds(0.8f);
						yield return new WaitForSeconds(IngameSetting.Instance.MoveBonusDelay);
					}
					battleNumSound = BattleNumSound.Small;
					defenderNum = ShowBattleNum(false, defenderNum, ++nNum); 
					tempTotalDefenderBonus--;
					nCount++;
					timeAdd = 0.0f;
				}
				yield return null;
			}
			
			isDefendResultDone = true;
		}		
		else
			isDefendResultDone = true;
		yield return new WaitForSeconds(0.5f);
		while(!isDefendResultDone || !isAttackResultDone)
			yield return null;
		
		battleNumSound = BattleNumSound.Big;
		// add dice effect
		if( attackerAddDiceCount>0 || defenderAddDiceCount>0 || attackerDelDiceCount>0 || 
			defenderDelDiceCount>0 || attackerSwapDiceCount>0 || defenderSwapDiceCount>0 ||
			attackerMultiplier > 1 || defenderMultiplier > 1
			)
		{
			iconSwappedToAttacker = null;
			iconSwappedToDefender = null;
			bool addDiceEffectDone = false;
			while(!addDiceEffectDone)
			{
				int nAttackNum = nAttackerDice + totalAttackerBonus;
				if(attackerAddDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(attacker.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i<attackerAddDiceCount;i++)
				{
					Vector3 newPos = attackerDiceIcon[i].obj.transform.position;
					if( IsPersonLeftSide(attacker) )
						newPos.x -= 0.122f;
					else
						newPos.x += 0.122f;
					CardManager.Instance.ShowPopupCardSkillEffect(attacker.SID, AbnormalType.MODIFY_BATTLE_DICE);
					attackerAddDiceIcon[i].Activate( ObjectPool.Spawn (diceIconPrefab, newPos) as DiceIconPrefab , attackerAddDice[i], i,true);
					BoardManager.Instance.RestartFSM(attackerAddDiceIcon[i].obj.GetComponent<PlayMakerFSM>());
					GameObject goEff = EffectManager.Instance.CreateEffectZ(13,newPos);
					Destroy(goEff,2.0f);
					yield return new WaitForSeconds(0.1f);
					nAttackNum += attackerAddDice[i];
					 
				}
				if(attackerAddDiceCount>0)
					attackerNum = ShowBattleNum(true,attackerNum, nAttackNum);

				int nDefenderNum = nDefenderDice + totalDefenderBonus;
				if(defenderAddDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(defender.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i<defenderAddDiceCount;i++)
				{
					Vector3 newPos = defenderDiceIcon[i].obj.transform.position;
					newPos.y -= 0.112f;

					defenderAddDiceIcon[i].Activate( ObjectPool.Spawn (diceIconPrefab, newPos) as DiceIconPrefab , defenderAddDice[i], i,false);
					BoardManager.Instance.RestartFSM(defenderAddDiceIcon[i].obj.GetComponent<PlayMakerFSM>());
					GameObject goEff = EffectManager.Instance.CreateEffectZ(13,newPos);
					Destroy(goEff,2.0f);
					yield return new WaitForSeconds(0.1f);
					nDefenderNum += defenderAddDice[i];
					
				}
				if(defenderAddDiceCount>0)
					defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum); 
				
				// dice del effect
				if(attackerDelDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(defender.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i< attackerDelDiceCount; i++)
				{
					DiceIcon diceIcon = FindDefenderIcon(attackerDelDice[i]);
					if(diceIcon!=null)
					{
						diceIcon.FadeOutDelete(5.0f);
						GameObject goEff = EffectManager.Instance.CreateEffectZ(13,diceIcon.obj.transform.position);
						Destroy(goEff,2.0f);
						nDefenderNum -= diceIcon.nDiceNum;
						defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum );						
					}
					
					yield return new WaitForSeconds(0.1f);
				}
				if(defenderDelDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(attacker.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i< defenderDelDiceCount; i++)
				{
					DiceIcon diceIcon = FindAttackerIcon(defenderDelDice[i]);
					if(diceIcon!=null)
					{
						diceIcon.FadeOutDelete(5.0f);
						GameObject goEff = EffectManager.Instance.CreateEffectZ(13,diceIcon.obj.transform.position);
						Destroy(goEff,2.0f);
						nAttackNum -= diceIcon.nDiceNum;
						attackerNum = ShowBattleNum(true, attackerNum, nAttackNum );						
					}					
					
					yield return new WaitForSeconds(0.1f);
				}				
				
				//swap dice effect
				isSwapMoveDone = false;
				bool isAttackerSwapHappened = false;
				if(attackerSwapDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(attacker.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i<attackerSwapDiceCount;i++)
				{
					DiceIcon attackerIcon = FindAttackerIcon(attackerGiveDice[i]);
					DiceIcon defenderIcon = FindDefenderIcon(attackerGetDice[i]);
					nAttackNum -= attackerGiveDice[i];
					nAttackNum += attackerGetDice[i];
					nDefenderNum += attackerGiveDice[i];
					nDefenderNum -= attackerGetDice[i];
					if( attackerIcon != null && defenderIcon != null)
					{
						StartCoroutine( SwapMoveDiceIcon(attackerIcon, defenderIcon) );
						attackerIcon.isSideChangedBySwap = true;
						defenderIcon.isSideChangedBySwap = true;
						iconSwappedToAttacker = defenderIcon;
						iconSwappedToDefender = attackerIcon;
					}
					isAttackerSwapHappened = true;
					yield return new WaitForSeconds(0.9f);
					glog.debug("swap nAttackNum="+ nAttackNum+ " nDefenderNum="+ nDefenderNum);
					attackerNum = ShowBattleNum(true, attackerNum, nAttackNum );
					defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum );
				}
				if(defenderSwapDiceCount>0)
					CardManager.Instance.ShowPopupCardSkillEffect(defender.SID, AbnormalType.MODIFY_BATTLE_DICE);
				for(int i=0; i<defenderSwapDiceCount;i++)
				{
					if(isAttackerSwapHappened)
						yield return new WaitForSeconds(0.2f);
					DiceIcon defenderIcon = FindDefenderIcon(defenderGiveDice[i]);
					DiceIcon attackerIcon = FindAttackerIcon(defenderGetDice[i]);
					nDefenderNum -= defenderGiveDice[i];
					nDefenderNum += defenderGetDice[i];
					nAttackNum += defenderGiveDice[i];
					nAttackNum -= defenderGetDice[i];
					if( attackerIcon != null && defenderIcon != null)
					{
						StartCoroutine( SwapMoveDiceIcon(attackerIcon, defenderIcon) );
						attackerIcon.isSideChangedBySwap = true;
						defenderIcon.isSideChangedBySwap = true;
						iconSwappedToAttacker = defenderIcon;
						iconSwappedToDefender = attackerIcon;
					}
					yield return new WaitForSeconds(0.9f);
					glog.debug("swap nAttackNum="+ nAttackNum+ " nDefenderNum="+ nDefenderNum);
					attackerNum = ShowBattleNum(true, attackerNum, nAttackNum );
					defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum );
				}
				
		//		if(attackerSwapDiceCount>0 || defenderSwapDiceCount>0)
		//		{
		//			glog.debug("swap nAttackNum="+ nAttackNum+ " nDefenderNum="+ nDefenderNum);
		//			attackerNum = ShowBattleNum(true, attackerNum, nAttackNum );
		//			defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum );
		//		}				
				
				// dice multipiler effect
				//attackerDoubleObj = null;
				//defenderDoubleObj = null;
				if(attackerMultiplier>1)
				{
					isDouble = true;
					nAttackNum = nAttackNum * attackerMultiplier;
					attackerNum = ShowBattleNum(true, attackerNum, nAttackNum );
					isDouble = false;
				}
				if(defenderMultiplier>1)
				{
					isDouble = true;
					nDefenderNum = nDefenderNum * defenderMultiplier;
					defenderNum = ShowBattleNum(false, defenderNum, nDefenderNum );
					isDouble = false;
				}
				
				//yield return new WaitForSeconds(0.1f);
				addDiceEffectDone = true;
				yield return null;
			}
		}
		
		BoardPerson winnerPerson = defender;
		BoardPerson loserPerson = attacker;
		if(winnerID == attackerID)
		{
			winnerPerson = attacker;
			loserPerson = defender;
		}
		
		if(isDrawVicroty)
		{
			if(isDrawDefeat)
			{
				if(loserPerson.isMe)
					UIManager.Instance.CardSkillNameShow( UIType.UI_DRAW_DEFEAT );		
				else
				{
					if( BoardManager.Instance.boardPersonNPCList.Contains( winnerPerson) )
						UIManager.Instance.CardSkillNameShow( UIType.UI_DRAW_DEFEAT );
					else
					{
						CardManager.Instance.ShowPopupCardSkillEffect(winnerID);
						UIManager.Instance.CardSkillNameShow( UIType.UI_DRAW_VICTORY );
					}
				}
			}
			else
			{
				CardManager.Instance.ShowPopupCardSkillEffect(winnerID);
				UIManager.Instance.CardSkillNameShow( UIType.UI_DRAW_VICTORY );
			}
		}

		if(maxCombatCount>1 && combatQueue.Count>0)
		{
			StartCoroutine("FadeOutNumAndIcons");
			PC_OP_COMBAT_RESULT packet = combatQueue.Dequeue();
			glog.debug("** combat again "+combatQueue.Count);
			yield return new WaitForSeconds(0.3f);
			CardManager.Instance.BattleEnd(winnerPerson.SID, loserPerson.SID , false);
			while(CardManager.Instance.isCoBattleEndRunning)
				yield return null;
			StageManagerWrapper.PP_CombatResult(packet);

			isRedice = false;
			isRematch = false;
		}
		else if(isRedice || isRematch)
		{

			StartCoroutine("FadeOutNumAndIcons");
			glog.debug("**  combat again ");
			SetMaxCombatCount(0);
			yield return new WaitForSeconds(0.3f);
			CardManager.Instance.BattleEnd(winnerPerson.SID, loserPerson.SID , false);
			while(CardManager.Instance.isCoBattleEndRunning)
				yield return null;

			combatCount=0;
			CardManager.Instance.battleManagerCombatCount=0;
			if(isRedice)
			{
				isRediceBattleDoing = true;
				CardManager.Instance.RediceEffect();
			}
			if(isRematch)
			{
				isRematchBattleDoing = true;
				CardManager.Instance.RematchEffect();
			}
			isRedice = false;
			isRematch = false;
			bDiceRolledDuringBattle = true;
			BoardManager.Instance.ActivateDiceOverHead(attacker, DiceShapeType.Attacker);
			if( StageManagerWrapper.manager.rollCombatDiceSID == BoardManager.Instance.mySID)
			{

				UIManager.Instance.ShowUIBattleRoll(true, StageManagerWrapper.combatRollDeadLine, DiceShapeType.Attacker);
			}
			if(bWaitAIThinking)
			{
				bWaitAIThinking=false;
				//BoardManager.Instance.ActivateDiceOverHead(attacker);
				BoardManager.Instance.ShowDiceUIBattle( attacker, null  , null, true);
			}
		}
		else
		{
			
			glog.debug(" --- all combat done ---");
			
			
			CardManager.Instance.BattleEnd(winnerPerson.SID, loserPerson.SID, true);

			if(winnerPerson.isMe)
				SoundManager.Instance.PlaySoundVoiceBattleWin();
			if(loserPerson.isMe)
				SoundManager.Instance.PlaySoundVoiceBattleLose();

			while(!CardManager.Instance.isCardWinAndBreakDone)
				yield return null;
			
			if(pushBackDelta!=0)
			{
				string temp = "";
				if(pushBackDelta>0) 
				{
					glog.debug("pushBackDelta effect "+pushBackDelta);
					CardManager.Instance.ShowLastActiveCardSkillEffect(winnerPerson.SID);
					temp = CStringTableManager.Instance.GetItemById(1685).Replace("{0}",pushBackDelta.ToString());//push back
				}
				else
				{
					glog.debug("pushBackDelta effect "+pushBackDelta);
					CardManager.Instance.ShowLastDeactiveCardSkillEffect(loserPerson.SID);
					pushBackDelta = -pushBackDelta;
					loserPerson.isPushBackResistActivated = true;
					temp = CStringTableManager.Instance.GetItemById(1684).Replace("{0}",pushBackDelta.ToString());//push back resist
				}
				UIManager.Instance.CardSkillNameShow(temp);
			}
			winnerPerson.PlayAttackAnim();
			//CardManager.Instance.WinnerCardAttack(winnerID, winnerPerson, loserID);
			while(!winnerPerson.bAttackEventTriggered)
				yield return null;
			glog.debug(" --- all combat done 2---");
			
			
			UIManager.Instance.BlackFocus(false);
			
			if(loserPerson.isBackExpelled)
				isBattleResultDone = true;

			StageManagerWrapper.camControl.SetBattleCameraFocus(false);

			// unit hp attack
			MainHUDUI.Instance.bEffectAttackUnitDone = true;
			if(deltaHPByAttack!=0)
			{
				glog.debug("############### deltahp "+deltaHPByAttack+"  loser="+loserID+"  attacker="+attackerID+"  defender="+defenderID+" attacked="+attackedSID);
				if(loserID == defenderID )//|| loserID == attackerID) 
				{
					//if(HaveToShowDetail(attackedSID)) 
					//{
			//			HudManager.Instance.EffectAttackUnit(loserPerson.transform.position ,attackedSID);
					//}
	
				}
			}

			//while(!MainHUDUI.Instance.bEffectAttackUnitDone)
			//	yield return null;

			HudManager.Instance.ShowHPChangeEffect_AfterBattle();
			
			
//			HudManager.Instance.ShowHPEffect(loserPerson,false,false);
	//		if(winnerPerson == defender)
	//			HudManager.Instance.ShowHPEffect(winnerPerson, false,false);
			
			yield return new WaitForSeconds(0.2f);

			AchievementCell.DoShowAchieve(winnerPerson,"kill");

			HudManager.Instance.ShowHPChangeEffect_AfterBattleCheckAvoidDeath();


			//for test long delay
			yield return new WaitForSeconds(0.3f);
			StartCoroutine("FadeOutNumAndIcons");
			yield return new WaitForSeconds(0.2f);
			
			//glog.debug("################# set attacker batleresultdone "+attacker.SID+"  "+attacker.isBattleResultDone);
			//attacker.isBattleResultDone = true;
			//glog.debug("################# set defender batleresultdone "+defender.SID+"  "+defender.isBattleResultDone);
			//defender.isBattleResultDone = true;
			isBattleResultDone = true;

			HudManager.Instance.ShowHPChangeEffect_AfterBattleByCard();
			HudManager.Instance.ShowMPChangeEffect(MPRegenType.UNIT_SKILL_EFFECT);

			if(BoardManager.Instance.boardPerson_me == winnerPerson)
				SoundManager.Instance.PlaySound(36);
			
			else if(BoardManager.Instance.boardPerson_me == loserPerson)
				SoundManager.Instance.PlaySound(37);

			AchievementCell.DoShowAchieve(winnerPerson,"combat_win");
			AchievementCell.DoShowAchieve(loserPerson,"combat_lose");
			

			UIManager.Instance.DisableSkillBar(false);

			StageManagerWrapper.camControl.EventZoomOut();
			isDuringBattle = false;

//			if(attacker.SID != BoardManager.Instance.curTurnSID)
//			{
//				HudManager.Instance.StopTurnAlarm(attacker.SID, false);
//			}
//			if(defender.SID != BoardManager.Instance.curTurnSID)
//			{
//				HudManager.Instance.StopTurnAlarm(defender.SID, false);
//			}

			yield return new WaitForSeconds(1.0f);

			if(attacker.tagOverHead!=null)
				attacker.tagOverHead.SetActive(true);
			if(defender.tagOverHead!=null)
				defender.tagOverHead.SetActive(true);

			BoardManager.Instance.ShowCurActiveDestMark();
		}

	}	
	
	IEnumerator FadeOutNumAndIcons()
	{
		FadeOutDiceIcons();

		tk2dSprite attackerNumTextMesh = attackerNum.GetComponent<tk2dSprite>();
		tk2dSprite defenderNumTextMesh = defenderNum.GetComponent<tk2dSprite>();
		tk2dSprite digit2Sprite_att = attackerNum.transform.FindChild("digit2").gameObject.GetComponent<tk2dSprite>();
		tk2dSprite digit2Sprite_def = defenderNum.transform.FindChild("digit2").gameObject.GetComponent<tk2dSprite>();

		tk2dSprite attDouble = null;
		tk2dSprite defDouble = null;
		tk2dSprite attDoubleX = null;
		tk2dSprite defDoubleX = null;
		if(attackerDoubleObj!=null) {
			attDouble = attackerDoubleObj.GetComponent<tk2dSprite>();
			attDoubleX = attackerDoubleObj.transform.FindChild("x").gameObject.GetComponent<tk2dSprite>();
		}
		if(defenderDoubleObj!=null) {
			defDouble = defenderDoubleObj.GetComponent<tk2dSprite>();
			defDoubleX = defenderDoubleObj.transform.FindChild("x").gameObject.GetComponent<tk2dSprite>();
		}

		Color originalAttackNumColor = attackerNumTextMesh.color;
		Color originalDefenderNumColor = defenderNumTextMesh.color;
		Color changeColor_attacker = originalAttackNumColor;
		Color changeColor_defender = originalDefenderNumColor;
		float alpha_num = 1.0f;
		while(alpha_num>0)
		{
			alpha_num -= 2.5f*Time.deltaTime;
			if(alpha_num <0)
				alpha_num = 0;
			changeColor_attacker.a = alpha_num;
			changeColor_defender.a = alpha_num;
			attackerNumTextMesh.color = changeColor_attacker;
			digit2Sprite_att.color = changeColor_attacker;
			//attackerNum.GetComponent<tk2dTextMesh>().Commit();
			defenderNumTextMesh.color = changeColor_defender;
			digit2Sprite_def.color = changeColor_defender;
			//defenderNum.GetComponent<tk2dTextMesh>().Commit();
			
			if(attDouble!=null) {
				attDouble.color = changeColor_attacker;
				attDoubleX.color = changeColor_attacker;
			}

			if(defDouble!=null) {
				defDouble.color = changeColor_defender;
				defDoubleX.color = changeColor_defender;
			}
			
			yield return null;
		}
		//Destroy(attackerDoubleObj);
		//Destroy(defenderDoubleObj);
		if(attackerDoubleObj!=null)
		{
			attackerDoubleObj.SetActive(false);
			attDouble.color = originalAttackNumColor;
			attDoubleX.color = originalAttackNumColor;
		}
		if(defenderDoubleObj!=null)
		{
			defenderDoubleObj.SetActive(false);
			defDouble.color = originalDefenderNumColor;
			defDoubleX.color = originalDefenderNumColor;
		}

		//Destroy(defenderNum);
		//Destroy(attackerNum);
		attackerNumTextMesh.color = originalAttackNumColor;
		defenderNumTextMesh.color = originalDefenderNumColor;
		digit2Sprite_att.color = originalAttackNumColor;
		digit2Sprite_def.color = originalDefenderNumColor;
		attackerNum.SetActive(false);
		defenderNum.SetActive(false);
	}

	//for exception case, clear at the time Turn Start
	void ClearNumAndIcons()
	{
		if(attackerNum!=null && attackerNum.activeSelf)
		{
			attackerNum.transform.parent = null;
			attackerNum.SetActive(false);
		}
		if(defenderNum!=null && defenderNum.activeSelf)
		{
			defenderNum.transform.parent = null;
			defenderNum.SetActive(false);
		}
		FadeOutDiceIcons();
	}
	
	IEnumerator SwapMoveDiceIcon(DiceIcon diceIcon1, DiceIcon diceIcon2)
	{
		diceIcon1.isMoving = true;
		diceIcon2.isMoving = true;
		GameObject go1 = diceIcon1.obj;
		GameObject go2 = diceIcon2.obj;
		Vector3 go1Pos = go1.transform.position;
		Vector3 go2Pos = go2.transform.position;

		Vector3 midPathVec1 = Vector3.zero;
		Vector3 midPathVec2 = Vector3.zero;
		float distX = Mathf.Abs(go1Pos.x-go2Pos.x);

		if(go1Pos.x < go2Pos.x)
		{
			midPathVec1 = new Vector3( go1Pos.x + distX/3, go1Pos.y + 0.25f, go1Pos.z);
			midPathVec2 = new Vector3( go2Pos.x - distX/3, go2Pos.y - 0.25f, go2Pos.z);
		}
		else
		{
			midPathVec1 = new Vector3(go1Pos.x - distX/3, go1Pos.y + 0.25f, go1Pos.z);
			midPathVec2 = new Vector3(go2Pos.x + distX/3, go2Pos.y - 0.25f, go2Pos.z);
		}
		Vector3 [] pathList1 = { go1.transform.position, midPathVec1, go2.transform.position };
		Vector3 [] pathList2 = { go2.transform.position, midPathVec2, go1.transform.position };
		//iTween.MoveTo(go1, iTween.Hash("time", 0.2f,"position", go2Pos, "easetype","easeInSine"));// , "oncomplete","SwapMoveDone") );
		//iTween.MoveTo(go2, iTween.Hash("time", 0.2f,"position", go1Pos, "easetype","easeInSine"));// , "oncomplete","SwapMoveDone") );

		LeanTween.scale(go1, new Vector3(1.3f,1.3f,1.0f), 0.1f).setEase(LeanTweenType.easeOutElastic);
		LeanTween.scale(go2, new Vector3(1.3f,1.3f,1.0f), 0.1f).setEase(LeanTweenType.easeOutElastic);
		yield return new WaitForSeconds(0.1f);

		iTween.MoveTo(go1, iTween.Hash("time", 0.4f, "path", pathList1,"movetopath",false, "easetype","easeInSine"));
		LeanTween.rotate(go1, new Vector3(0,0, 540f), 0.4f);
		LeanTween.scale(go1, new Vector3(1.0f,1.0f,1.0f), 0.4f);

		iTween.MoveTo(go2, iTween.Hash("time", 0.4f, "delay", 0.2f,  "path", pathList2,"movetopath",false, "easetype","easeInSine"));
		LeanTween.rotate(go2, new Vector3(0,0, 540f), 0.6f);
		LeanTween.scale(go2, new Vector3(1.0f,1.0f,1.0f), 0.6f);

		yield return new WaitForSeconds(0.4f);
		SwapMoveDone(diceIcon1);

		yield return new WaitForSeconds(0.2f);
		SwapMoveDone(diceIcon2);

	//	StartCoroutine(SwapMoveDone(diceIcon1, 0.4f) );
	//	StartCoroutine(SwapMoveDone(diceIcon2, 0.4f+0.2f) );
	}
	
	void SwapMoveDone(DiceIcon diceIcon)
	{
		//glog.debug("swap move done");
		//isSwapMoveDone = true;
		//yield return new WaitForSeconds(delay);
		diceIcon.isMoving = false;
		GameObject goEff = EffectManager.Instance.CreateEffectZ(13, diceIcon.obj.transform.position);
		Destroy(goEff,2.0f);
	}
	
	void ShowMoveBonus(BoardPerson person, Transform destTrans, int index, string prefix, int nAddNum, DiceShapeType diceShape)
	{
		bool isAnchorTopRight;
		if(person.isMe)
		{
			isAnchorTopRight = false;
			MainHUDUI.Instance.ShowMoveBonus(person, destTrans, index, prefix, nAddNum, isAnchorTopRight, diceShape);
		}
		else if(person.isBoss)
		{
			isAnchorTopRight = true;
			MainHUDUI.Instance.ShowMoveBonus(person, destTrans, index, prefix, nAddNum, isAnchorTopRight, diceShape);
		}
	}
	
	bool HaveToShowDetail(int sid)
	{
		if(sid == BoardManager.Instance.mySID )//|| sid == EnemyUnitUI.Instance.mySID)
			return true;
		return false;
	}
	
//	GameObject ShowBattleNum_old(GameObject objNum, float x, float y, int nNum)
//	{
//		if(objNum)
//			Destroy(objNum);
//		objNum = Instantiate(battleResultNumPrefab) as GameObject;
//	    objNum.GetComponent<tk2dTextMesh>().text = nNum.ToString();
//		float modScale = 0.065f;
//		if(nNum>12)
//			modScale = 0.091f;
//		else if(nNum>2)
//		{
//			modScale = modScale + (nNum - 2) * 0.0026f;
//			if(modScale>0.091f)
//				modScale=0.091f;
//		}
//		objNum.GetComponent<tk2dTextMesh>().scale = new Vector3( modScale, modScale, 0);
//	    objNum.GetComponent<tk2dTextMesh>().Commit();
//		//objNum.GetComponent<tk2dTextMesh>().renderer.bounds.center
//		objNum.transform.position = new Vector3( x, y, objNum.transform.position.z);	
//		return objNum;
//	}

	public GameObject ShowBattleNum_Attacker(BoardPerson person, int nNum)
	{
		attacker = person;
		attackerNum = ShowBattleNum(true, attackerNum, nNum);
		//ShowAttackerDiceIcon();
		return attackerNum;
	}

	public GameObject ShowBattleNum_Defender(BoardPerson person, int nNum)
	{
		defender = person;
		defenderNum = ShowBattleNum(false, defenderNum, nNum);
		//ShowDefenderDiceIcon();
		return defenderNum;
	}
	
	GameObject ShowBattleNum(bool isAttacker, GameObject objNum, int nNum)
	{
		if(battleNumSound == BattleNumSound.Small)
			SoundManager.Instance.PlaySound(4);
		else if(battleNumSound == BattleNumSound.Big)
			SoundManager.Instance.PlaySound(3);
		
		if(objNum)
		{
			objNum.SetActive(false);
		}
		
		objNum.SetActive(true);
		if(isAttacker)
		{
			objNum = attackerNum;
		//	attackerNumFsm.enabled = false;
		//	attackerNumFsm.Fsm.Stop();	
//			BoardManager.Instance.RestartFSM(attackerNumFsm);
		}
		else
		{
			objNum = defenderNum;
		//	defenderNumFsm.enabled = false;
		//	defenderNumFsm.Fsm.Stop();			
//			BoardManager.Instance.RestartFSM(defenderNumFsm);
		}
		
		
		tk2dSprite numSprite = objNum.GetComponent<tk2dSprite>();
		GameObject digit2Go = objNum.transform.FindChild("digit2").gameObject;
		digit2Go.SetActive(false);
		tk2dSprite digit2Sprite = digit2Go.GetComponent<tk2dSprite>();

		numSprite.scale = new Vector3( 0.1f, 0.1f, 1);
		digit2Sprite.scale = new Vector3( 0.1f, 0.1f, 1);

//		if(isAttacker)
//			textMesh.color = IngameSetting.Instance.GetPlayerColor( attacker.gameOrder);
//		else
//			textMesh.color = IngameSetting.Instance.GetPlayerColor( defender.gameOrder);
		string prefixSprite = "No_D";
		if(isAttacker)
			prefixSprite = "No_C";

		if(nNum>9)
		{
			digit2Go.SetActive(true);
			int nDigit1 = nNum % 10;
			int nDigit2 = nNum / 10;
			digit2Go.GetComponent<tk2dSprite>().SetSprite(prefixSprite+nDigit2.ToString());
			numSprite.SetSprite (prefixSprite+nDigit1.ToString());
		}
		else
		{
			numSprite.SetSprite (prefixSprite+nNum.ToString());
		}

		float modScale = GetBattleNumModScale(nNum);
		numSprite.scale = new Vector3( modScale, modScale, 1);
		digit2Sprite.scale = new Vector3( modScale, modScale, 1);
	    

		BoardPerson person = defender;
		if(isAttacker)
			person = attacker;

		float up_offset = battleNumYOffset + BoardPerson.upOffset;
		float offset_x = SetNumOffset(nNum, objNum, person);

//		if(isAttacker)
//			attackerNumSprite = numSprite;
//		else
//			defenderNumSprite = numSprite;
		
//		if(isAttacker)
//			RepositionDiceIcon(attacker, attackerTextMesh, attackerDiceIcon);
//		else
//			RepositionDiceIcon(defender, defenderTextMesh, defenderDiceIcon);


		if(isDouble)
		{
			glog.debug("double effect show");
			GameObject doubleObj;
			if(isAttacker)
			{
				if(doubleNumPrefab_attacker==null)
					doubleNumPrefab_attacker = Resources.Load("Prefabs/Ingame/DoubleNum_att") as GameObject;
				if(attackerDoubleObj==null)
					attackerDoubleObj = Instantiate(doubleNumPrefab_attacker) as GameObject;
				attackerDoubleObj.SetActive(true);
				doubleObj = attackerDoubleObj;
			}
			else
			{
				if(doubleNumPrefab_defender==null)
					doubleNumPrefab_defender = Resources.Load("Prefabs/Ingame/DoubleNum_def") as GameObject;
				if(defenderDoubleObj==null)
					defenderDoubleObj = Instantiate(doubleNumPrefab_defender) as GameObject;	
				defenderDoubleObj.SetActive(true);
				doubleObj = defenderDoubleObj;
			}
			tk2dSprite txt = doubleObj.GetComponent<tk2dSprite>();
			if(isAttacker)
			{
				txt.SetSprite(prefixSprite+attackerMultiplier.ToString() );
			}
			else
			{
				txt.SetSprite(prefixSprite+defenderMultiplier.ToString() );
			}
			//txt.scale = new Vector3( modScale, modScale, 0);	
			//doubleObj.transform.FindChild("x").gameObject.GetComponent<tk2dSprite>().scale = new Vector3( modScale, modScale, 0);
			
			float addUpOffset = txt.renderer.bounds.size.y + 0.04f;
			doubleObj.transform.position = new Vector3( person.transform.position.x + offset_x , person.transform.position.y + up_offset + addUpOffset, doubleObj.transform.position.z);
			//Destroy(doubleObj,1.0f);

			Vector3 doubleEffPos = doubleObj.transform.position;
			//GameObject eff = EffectManager.Instance.CreateEffectZ(16, doubleObj.transform.position);
			//glog.debug("double effect  "+eff.name);
			//Destroy(eff,2.0f);
			EffectManager.Instance.DoubleEffect(doubleEffPos);
		}

		if(isAttacker)
			BoardManager.Instance.RestartFSM(attackerNumFsm);
		else
			BoardManager.Instance.RestartFSM(defenderNumFsm);
		
		return objNum;
	}

	void SetOffsetFor2Digit(int nNum, GameObject objNum)
	{
		float offset_x=0;
		if(nNum>0)
		{
			if(nNum>9)
				offset_x += 0.076f;
		}
		if(offset_x>0)
		{
			Vector3 newPos = objNum.transform.position;
			newPos.x += offset_x;
			objNum.transform.position = newPos;
		}
	}

	float SetNumOffset(int nNum, GameObject objNum, BoardPerson person)
	{
		float offset_x = 0.1f;
		
		if(IsPersonLeftSide(person))
			offset_x = -offset_x;

		if(nNum>0)
		{
			if(nNum>9)
				offset_x += IngameSetting.Instance.digit2Offset;
		}
		
		float up_offset = battleNumYOffset + BoardPerson.upOffset;
		objNum.transform.position = new Vector3( person.transform.position.x + offset_x , person.transform.position.y + up_offset, objNum.transform.position.z);	
		//glog.debug(nNum+"  offset_x "+offset_x);
		return offset_x;
	}

	float SetNumOffset(GameObject objNum, BoardPerson person)
	{
		return SetNumOffset(0,objNum,person);
	}

	public bool IsPersonLeftSide(BoardPerson person)
	{
		if( person.moveDir == MoveDir.TopRight || person.moveDir == MoveDir.BottomRight )
			return true;
		return false;
	}
	
//	float GetBattleNumModScale(int nNum)
//	{
//		float modScale = 0.065f;
//		if(nNum>12)
//			modScale = 0.091f;
//		else if(nNum>2)
//		{
//			modScale = modScale + (nNum - 2) * 0.0026f;
//			if(modScale>0.091f)
//				modScale=0.091f;
//		}
//		return modScale;
//	}

	float GetBattleNumModScale(int nNum)
	{
		float modScale = 0.07f;
		if(nNum>12)
			modScale = 0.1f;
		else if(nNum>2)
		{
			modScale = modScale + (nNum - 2) * (0.1f-0.07f);
			if(modScale>0.1f)
				modScale=0.1f;
		}
		return modScale;
	}

	public void SetMaxCombatCount(int i)
	{
		maxCombatCount = i;
	}
	
	
//	IEnumerator ShowBattleBonusDice(int nBonus, Vector3 pos, Color c)
//	{
//		yield return new WaitForSeconds(0.15f);
//		GameObject go = Instantiate(battleResultNumPrefab) as GameObject;
//	    go.GetComponent<tk2dTextMesh>().text = "+"+nBonus.ToString();
//		go.GetComponent<tk2dTextMesh>().color = c;
//		go.GetComponent<tk2dTextMesh>().scale = new Vector3(0.8f,0.8f,0.8f);
//	    go.GetComponent<tk2dTextMesh>().Commit();
//		go.transform.position = new Vector3(pos.x, pos.y + 0.1257f, pos.z);
//	}
	
//	IEnumerator ShowBattleWinLoseUI()
//	{
//		yield return new WaitForSeconds(0.2f);		
//		GameObject go=null;
//		if(BattleManager.Instance.nTypeBattleResultUI == 1) {
//			go = Instantiate(battleWinPrefab) as GameObject;
//		}
//		else if(BattleManager.Instance.nTypeBattleResultUI == 2) {
//			go = Instantiate(battleLosePrefab) as GameObject;
//		}
//		if(go!=null) {
//			go.transform.position = new Vector3( boardPerson_me.transform.position.x, boardPerson_me.transform.position.y+0.2f, go.transform.position.z);
//			go.transform.parent = boardPerson_me.transform;
//		}
//		BattleManager.Instance.nTypeBattleResultUI = 0;
//	}
	
}
